<template>
  <div class="tabs-content">
    <el-tabs
      v-model="editableTabsValue"
			class="tabs-boxs"
      type="card"
      @tab-click="handleClick"
      @tab-remove="removeTab"
    >
      <el-tab-pane v-if="showHomeTab" name="home">
        <span slot="label">
          <i class="el-icon-s-home" />
        </span>
      </el-tab-pane>
      <el-tab-pane
        v-for="(item, index) in editableTabs"
        :key="item.meta.only"
        :label="item.meta.title"
				:title="item.meta.title"
        :name="item.meta.only"
        :closable="editableTabs.length > 1"
      />
    </el-tabs>
  </div>
</template>
<script>
export default {
  name: 'Tabs',
  props: {
    type: {
      type: String,
      default: () => {}
    },
    showHomeTab: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      editableTabsValue: '',
      activeName: '',
      editableTabs: []
    }
  },
  computed: {
  },
  watch: {
    type() {
      this.editableTabs = []
    },
    $route(val) {
      this.addTab(val)
    }
  },
  mounted() {
    this.addTab(this.$route)
  },
  methods: {
    handleClick(e) {
			const { name, query, meta } = this.editableTabs[e.index]
      if (this.activeName === meta.only) return
      this.activeName = meta.only

      if (name === 'home') {
        this.$router.push({ name: "" })
      } else {
        this.$router.push({ name: name, query: query })
      }
    },
    addTab(targetName) {
			let routeVal = { name: "", meta: {}, query: {} }
			routeVal.name = targetName.name
			routeVal.meta.title = targetName.meta.title || targetName.query.rorterName
			routeVal.meta.only = targetName.query.rorterName ? targetName.name + targetName.query.id : targetName.name
			for(let key in targetName.query){
				routeVal.query[key] = targetName.query[key]
			}
			this.activeName = routeVal.meta.only
			let flag = false
			for (let i = 0; i < this.editableTabs.length; i++) {
				if (this.editableTabs[i].meta.only === routeVal.meta.only) {
					flag = true
					break
				}
			}
			// 判断有，且是前台展示
			if (!flag && targetName.meta[this.type]) {
				this.editableTabs.push(routeVal)
			}
			this.editableTabsValue = routeVal.meta.only
    },
    removeTab(targetName) {
      const tabs = Object.assign([], this.editableTabs)
      let activeName = this.editableTabsValue
			let pagenData = {}
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.meta.only === targetName) {
            const nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
							pagenData = nextTab
              activeName = nextTab.meta.only
            }
          }
        })
      }
      if (this.editableTabsValue !== activeName) {
        this.$router.push({ name: pagenData.name, query: pagenData.query })
      }
			this.editableTabsValue = activeName
			this.editableTabs = tabs.filter((tab) => tab.meta.only !== targetName)
    }
  }
}
</script>
<style lang="scss">

</style>
